import { Effect, Reducer } from 'umi';

import { getSheetList, getSheetListByProjrctId, saveEditModel } from '@/services/analysis';

import { ISheetItem } from '../type';

export interface SheetModelState {
  sheetList: Array<ISheetItem>;
  panelsParentList: Array<{ name: string; id: number }>;
}

export interface SheetModelType {
  namespace: 'sheet';
  state: SheetModelState;
  effects: {
    fetchSheetList: Effect;
    fetchSheetListByProjectId: Effect;
    saveEditSheet: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const SheetModel: SheetModelType = {
  namespace: 'sheet',

  state: {
    sheetList: [],
    panelsParentList: [],
  },

  effects: {
    // 获取权限范围内的所有视图
    * fetchSheetList({ callback }, { call, put }: any) {
      let response = yield call(getSheetList);
      let treeData: Array<{ name: string; id: number }> = [];

      // 数据表列表
      yield put({
        type: 'save',
        payload: { sheetList: response.payload },
      });
      if (response && response.payload) {
        // 获取树形结构父级 项目级
        response.payload.foreach((item: ISheetItem) => {
          const obj = {
            id: item.project.id,
            name: item.project.name,
          };
          if (JSON.stringify(treeData).indexOf(JSON.stringify(obj)) === -1) {
            treeData.push(obj);
          }
        });

        // 默认回调请求第一个指标详情
        callback && callback(response.payload);
      }


      // 数据表项目列表
      yield put({
        type: 'save',
        payload: { panelsParentList: treeData },
      });
    },
    * fetchSheetListByProjectId({ payload,callback }, { call, put }: any) {
      let response = yield call(getSheetListByProjrctId,payload);
      // 数据表列表
      yield put({
        type: 'save',
        payload: { sheetList: response.payload },
      });
      if (response && response.payload) {
        // 默认回调请求第一个指标详情
        callback && callback(response.payload);
      }
    },

    // 存储修改数据表
    * saveEditSheet({ payload, callback }: any, { call }: any) {
      const response = yield call(saveEditModel, payload);

      if (callback) callback(response);
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default SheetModel;
